package muhnes.sizoo.dal;

import java.util.List;
import javax.annotation.PreDestroy;
import muhnes.sizoo.HibernateUtilZoologia;
import muhnes.sizoo.modelo.Departamento;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DepartamentoDaoImpl implements DepartamentoDao {
    
    Session sesion;
    
    public DepartamentoDaoImpl() {
        sesion = HibernateUtilZoologia.getSessionFactory().openSession();
    }
    
    @PreDestroy
    public void destroy() {
        sesion.close();
    }

    @Override
    public void guardar( Departamento departamento ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.save( departamento );
        transaccion.commit();
    }

    @Override
    public void guardarColeccion( List< Departamento > departamentos ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.saveOrUpdate( departamentos );
        transaccion.commit();
    }

    @Override
    public void actualizar( Departamento departamento ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.update( departamento );
        transaccion.commit();
    }

    @Override
    public void actualizarColeccion( List< Departamento > departamentos ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.update( departamentos );
        transaccion.commit();
    }

    @Override
    public void eliminar( Departamento departamento ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.delete( departamento );
        transaccion.commit();
    }

    @Override
    public void eliminarColeccion( List< Departamento > departamentos ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.delete( departamentos );
        transaccion.commit();
    }

    @Override
    public void eliminarPorId( int id ) {
        Transaction transaccion = sesion.beginTransaction();
        Departamento departamento = buscarPorId( id );
        sesion.delete( departamento );
        transaccion.commit();
    }

    @Override
    public Departamento buscarPorId( int id ) {
        Transaction transaccion = sesion.beginTransaction();
        Query consulta = sesion.createQuery("from Departamento where codigodepartamento = " + id);
        Departamento departamento = (Departamento)consulta.uniqueResult();
        transaccion.commit();
        return departamento;
    }

    @Override
    public List< Departamento > buscarTodos() {
        Transaction transaccion = sesion.beginTransaction();
        Query consulta = sesion.createQuery("from Departamento");
        List< Departamento > departamentos = consulta.list();
        transaccion.commit();
        return departamentos;
    }

}
